//监听值的变化，自适应---------------------
$('#inputword').bind('input propertychange', function(a) {
    //console.log(a.target);
    var a= a.target;
    //自适应高度
    console.log(a.rows);
    //if(!row){row=1;};
    var wid=document.getElementById("inputword").style.width;
    //a.cols=parseInt((wid-10)/15);
    if(a.cols==0){a.cols=20}
    var col=a.cols;
    var val=a.value.length;
    var rownum=1;
    console.log("col",col);
    console.log("val.length",val);
    if(val>=col){
        rownum=Math.ceil(val/col);
        console.log("rownum",rownum);
        if(rownum>=3){
            a.style.overflowY="auto";
            a.rows=3;
        }else{
            a.rows=rownum;
        }
    }
});
//表情 输入框不能同时存在-------------------------------
$("#inputword").focus(function(){
    $(".hide").css("display","none");
});
//页面底部定位------------------------------------------
function tobottom(){
    console.log("页面滚动底部方法");
    var chatbody= document.getElementById('chatbody');
    chatbody.scrollTop = chatbody.scrollHeight;
}
//展示大图片--------------------------------------------
function showbigimg(e){
    $("#digimgplace").css("display","block");
    $("#digimgplace").css("background-image","url('"+e.src+"')");
}
//关闭大图----------------------------------------------
$("#digimgplace").click(function(){
    $("#digimgplace").css("display","none");
});
//===================================================获取用户ID=========================================================
var id=$.cookie("MYID");
//var id="7c7fdd2ef9a51aed";
//var otherid ="88dbe0b80fed6bc5";
if(id){

}else{
    location.href="index.html";
}
var regotherid=/(otherid=)([a-zA-Z0-9]*)/;
var otherid = urlfrom.match(regotherid).splice("=")[2];
//var otherid ="88dbe0b80fed6bc5";
//跳转按键
document.getElementsByClassName("mweb_modal_back_button")[0].onclick=function(){
    history.go(-1);
};
document.getElementsByClassName("header_action_buttons")[0].onclick=function(){
    location.href="otherpeoplepage.html?otherid="+otherid;
};
//环信建立连接
var conn = new WebIM.connection({
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions
});
//时间方法---------------------------------------------------------
function GetDateT(){
    var d,s;
    d = new Date();
    //s = d.getYear() + "-";             //取年份
    //s = s + (d.getMonth() + 1) + "-";//取月份
    //s= d.getDate() + " ";         //取日期
    s = d.getHours() + ":";       //取小时
    s += d.getMinutes() ;    //取分
    //s += d.getSeconds();         //取秒
    return(s);
}
var oldtime=GetDateT();//保存上一次时间
//获取聊天对象信息-------------------------------------------------
var otherimg="";//保存他人头像
var myimg="";//保存自己头像
$.ajax({//别人的头像
    type: "post",
    //提交的网址
    url: userurl,
    //提交的数据
    data: { "userId": otherid },
    //返回数据的格式
    datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
    success:function(data){
        $(".page_title.unified span").html(data.Data.nick);
        if(data.Data.userAva){
            otherimg="<img src='http://42.62.66.198:8003/"+data.Data.userAva+"'>";
        }else{
            otherimg="<img src='img/af8.png'>";
        }
    }
});
$.ajax({//自己的头像
    type: "post",
    //提交的网址
    url: userurl,
    //提交的数据
    data: { "userId": id},
    //返回数据的格式
    datatype: "json",//"xml", "html", "script", "json", "jsonp", "text".
    success:function(data){
        if(data.Data.userAva){
            myimg="<img src='http://42.62.66.198:8003/"+data.Data.userAva+"'>";
        }else{
            myimg="<img src='img/af8.png'>";
        }
    }
});

//登录
var options = {
    apiUrl: WebIM.config.apiURL,
    user:id,
    pwd:id,
    appKey: "pulu#pulu"
};
conn.open(options);
//收信息
conn.listen({
    onOpened: function ( message ) {          //连接成功回调
        //如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
        conn.setPresence();
        console.log("连接成功:");
        //console.log(message)
    },
    onTextMessage: function ( message ) {//收到文本消息
        //console.log("收到的文本消息");
        //console.log(message);
        var arr1=message.data;
        //console.log(arr1);
        arr1=codetoface(arr1);
        var imgheight=$(".img").width();
        var newtime=GetDateT();
        if(newtime==oldtime){
            //console.log("时间相等");
            $("#chatbody").append("<div class='otherchatword'> <div class='img' style='height:33px;width:33px;'> "+otherimg+" </div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
            tobottom();
        }else{
            //console.log("时间不等");
            oldtime=newtime;
            $("#chatbody").append("<div class='otherchatword'> <div class='showtime'><span>"+newtime+"</span></div><div class='img' style='height:33px;width:33px;'> "+otherimg+" </div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
            tobottom();
        }

        //$(".img").height($(".img").width());

    },
    onClosed: function ( message ) {console.log("1");},         //连接关闭回调
    onEmojiMessage: function ( message ) {console.log("2");},   //收到表情消息
    onPictureMessage: function ( message ) {//收到图片消息
        console.log(message);
        var newtime=GetDateT();
        if(newtime==oldtime){
            $("#chatbody").append("<div class='otherchatword'> <div class='img'> "+otherimg+" </div> <div class='word' style='padding:2px;'><p class='arrow'></p><img onclick='showbigimg(this)' class='getimg' src='"+message.url+"' onload='tobottom()'></div> </div>");
            $(".img").height($(".img").width());
        }else{
            oldtime=newtime;
            $("#chatbody").append("<div class='otherchatword'><div class='showtime'><span>"+newtime+"</span></div> <div class='img'> "+otherimg+" </div> <div class='word' style='padding:2px;'><p class='arrow'></p><img onclick='showbigimg(this)' class='getimg' src='"+message.url+"' onload='tobottom()'></div> </div>");
            $(".img").height($(".img").width());
        }

    },
    onCmdMessage: function ( message ) {console.log("4");},     //收到命令消息
    onAudioMessage: function ( message ) {console.log("5");},   //收到音频消息
    onLocationMessage: function ( message ) {console.log("6");},//收到位置消息
    onFileMessage: function ( message ) {console.log("7");},    //收到文件消息
    onVideoMessage: function ( message ) {console.log("8");},   //收到视频消息
    onPresence: function ( message ) {console.log("9");console.log(message);},       //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
    onRoster: function ( message ) {console.log("10");},         //处理好友申请
    onInviteMessage: function ( message ) {console.log("11");},  //处理群组邀请
    onOnline: function () {console.log("本机网络连接成功12");},                  //本机网络连接成功
    onOffline: function () {console.log("本机网络掉线13");},                 //本机网络掉线
    onError: function ( message ) {console.log("失败回调14");console.log(message)}           //失败回调
});
//发送聊天信息
var sendword=document.getElementById("sendword");//按钮
document.onkeydown=function(event){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode==13){ // enter 键
        if(document.getElementById("inputword").value&&!document.getElementById("inputword").value.match(/^\s+$/g)){
            var id = conn.getUniqueId();//生成本地消息id
            var msg = new WebIM.message('txt', id);//创建文本消息
            //判断是否有表情
            var arr1=document.getElementById("inputword").value;
            arr1=codetoface(arr1);
            msg.set({
                msg:document.getElementById("inputword").value,
                to:otherid,
                success:function(id,serverId){
                    //console.log("发送信息成功");
                    //console.log(id);
                    //console.log(serverId);
                    var newtime=GetDateT();
                    if(newtime==oldtime){
                        document.getElementById("inputword").rows="1";
                        $("#chatbody").append("<div class='mychatword'> <div class='img'>"+myimg+"</div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
                        console.log($(".img").width());
                        $(".img").height($(".img").width());
                        $("#inputword").val("");
                        tobottom();
                        $("#sendword").attr("class","cannotclick");
                        $("#inputword").blur();
                    }else{
                        oldtime=newtime;
                        document.getElementById("inputword").rows="1";
                        $("#chatbody").append("<div class='mychatword'> <div class='showtime'><span>"+newtime+"</span></div>  <div class='img'>"+myimg+"</div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
                        //console.log($(".img").width());
                        $(".img").height($(".img").width());
                        $("#inputword").val("");
                        tobottom();
                        $("#sendword").attr("class","cannotclick");
                        $("#inputword").blur();
                    }
                }
            });
            conn.send(msg.body);
        }
    }
};
sendword.onclick=function(){
    if(document.getElementById("inputword").value&&!document.getElementById("inputword").value.match(/^\s+$/g)){
        var id = conn.getUniqueId();//生成本地消息id
        var msg = new WebIM.message('txt', id);//创建文本消息
        //判断是否有表情
        var arr1=document.getElementById("inputword").value;
        arr1=codetoface(arr1);
        msg.set({
            msg:document.getElementById("inputword").value,
            to:otherid,
            success:function(id,serverId){
                //console.log("发送信息成功");
                //console.log(id);
                //console.log(serverId);
                var newtime=GetDateT();
                if(newtime==oldtime){
                    document.getElementById("inputword").rows="1";
                    $("#chatbody").append("<div class='mychatword'> <div class='img'>"+myimg+"</div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
                    //console.log($(".img").width());
                    $(".img").height($(".img").width());
                    $("#inputword").val("");
                    tobottom();
                    $("#sendword").attr("class","cannotclick");
                    $("#inputword").blur();
                }else{
                    oldtime=newtime;
                    document.getElementById("inputword").rows="1";
                    $("#chatbody").append("<div class='mychatword'> <div class='showtime'><span>"+newtime+"</span></div>  <div class='img'>"+myimg+"</div> <div class='word'><p class='arrow'></p>"+arr1+"</div> </div>");
                    //console.log($(".img").width());
                    $(".img").height($(".img").width());
                    $("#inputword").val("");
                    tobottom();
                    $("#sendword").attr("class","cannotclick");
                    $("#inputword").blur();
                }
            }
        });
        conn.send(msg.body);
    }
};
//打开表情
var mySwiper;
$(".face").click(function(){
    if(document.getElementById("facelist").style.display==="block"){
        document.getElementById("facelist").style.display="none";
    }else if(document.getElementById("facelist").style.display==="none"){
        document.getElementById("facelist").style.display="block";
        if(!mySwiper){
            mySwiper = new Swiper ('.swiper-container', {
                paginationClickable: true,
                touchRatio : 1,
                initialSlide :0,
                pagination: '.swiper-pagination'
            })
        }
    }
});
//发送表情
function sendface(e){
    var face=e.dataset.key;
    $("#sendword").attr("class","");
    $("#inputword").insertAtCaret(face);
    $("#inputword").blur();
}
//$().ready(
//    function(){
//        var id = conn.getUniqueId();
//        var msg = new WebIM.message('img', id);
//        var input = document.getElementById('addimgbtn');//选择图片的input
//        var file = WebIM.utils.getFileUrl(input);
//        var allowType = {
//            "jpg": true,
//            "gif": true,
//            "png": true,
//            "bmp": true
//        }
//    }
//)

//上传图片
document.getElementById("addimgbtn").addEventListener( 'change',createimg,false );
function createimg(){
    var id = conn.getUniqueId();
    var msg = new WebIM.message('img', id);
    var input = document.getElementById('addimgbtn');//选择图片的input
    var file = WebIM.utils.getFileUrl(input);
    console.log(file);
    var allowType = {
        "jpg": true,
        "jpeg": true,
        "gif": true,
        "png": true,
        "bmp": true
    };
    if ( file.filetype.toLowerCase() in allowType ) {
        var imgurl="";
        msg.set({
            apiUrl: WebIM.config.apiURL,
            file: file,
            to: otherid,
            onFileUploadError: function ( error ) {
                console.log("发送图片失败");
            },//图片上传失败
            onFileUploadComplete: function ( data ) {
                console.log("发送图片部分");
                //图片地址：data.uri + '/' + data.entities[0].uuid;
                console.log(data.uri + '/' + data.entities[0].uuid);
                imgurl=data.uri + '/' + data.entities[0].uuid;
            },
            success: function ( id, serverMsgId ) {
                console.log("发送图片成功");
                console.log(id);
                console.log(serverMsgId);
                var newtime=GetDateT();
                if(newtime==oldtime){
                    $("#chatbody").append("<div class='mychatword'> <div class='img'>"+myimg+"</div> <div class='word' style='padding:2px;'><p class='arrow'></p><img onclick='showbigimg(this)' class='getimg' src='"+imgurl+"' onload='tobottom()'></div> </div>");
                }else{
                    oldtime=newtime;
                    $("#chatbody").append("<div class='mychatword'> <div class='showtime'><span>"+newtime+"</span></div>  <div class='img'>"+myimg+"</div> <div class='word' style='padding:2px;'><p class='arrow'></p><img onclick='showbigimg(this)' class='getimg' src='"+imgurl+"' onload='tobottom()'></div> </div>");
                }

            },//图片消息发送成功
            flashUpload: WebIM.flashUpload
        });
        conn.send(msg.body);
    }
};